<template>
  <div class="major-list">
    <div class="search-input">
      <el-select
        v-model="tagName"
        multiple
        filterable
        remote
        reserve-keyword
        collapse-tags
        placeholder="输入专业名称查询适配产业"
        no-data-text="输入专业名称查询适配产业"
        :remote-method="handleRemoteMethod"
        @change="handleChangeMajor"
        style="width: 100%"
        popper-class="my-select"
      >
        <template #prefix>
          <img class="search-icon" :src="searchIcon" alt="" />
        </template>
        <el-option
          v-for="item in searchResult"
          :key="item.positionTagId"
          :label="item.tagName"
          :value="item.positionTagId"
        />
      </el-select>
    </div>
    <div class="header-tabs">
      <div class="tabs-list">
        <div
          class="tab-item"
          :class="{ active: currentSchool == item.value }"
          v-for="item in schoolLevelList"
          :key="item.value"
          @click="handleChangeSchool(item)"
        >
          {{ item.label }}
        </div>
      </div>

      <div class="reset-box" @click="clearSelectedMajors(true)">
        <img src="@/assets/images/industryMap/reset.png" alt="" />
        重置
      </div>
    </div>
    <!-- first major -->
    <div class="first-major" v-if="majorData[currentSchool]?.length">
      <div class="first-major-list">
        <div
          class="first-major-item"
          :class="
            item.positionTagId == currentFirstMajor.positionTagId
              ? 'active'
              : ''
          "
          v-for="item in majorData[currentSchool]"
          :key="item.positionTagId"
          @click="selectFirstMajor(item)"
        >
          {{ item.tagName }}
        </div>
        <div class="swiper-slide"></div>
      </div>
    </div>
    <!-- 专业二级/三级分类 -->
    <div class="major-child-main">
      <div class="major-second">
        <div
          class="major-second-item"
          :class="
            item.positionTagId == currentSecondMajor.positionTagId
              ? 'active'
              : ''
          "
          v-for="item in currentFirstMajor.children"
          :key="item.positionTagId"
          @click="selectSecondMajor(item)"
        >
          {{ item.tagName }}
        </div>
      </div>
      <div class="major-third">
        <div
          class="major-third-item"
          :class="isAllSelected ? 'active' : ''"
          @click="toggleSelectAll"
        >
          <span>全选</span>
          <img
            class="checked-img"
            :src="isAllSelected ? checkedImg : unCheckedImg"
            alt=""
          />
        </div>
        <div
          class="major-third-item"
          :class="item.checked ? 'active' : ''"
          v-for="item in currentSecondMajor.children"
          :key="item.positionTagId"
          @click="handleSelectMajor(item)"
        >
          <span> {{ item.tagName }}</span>
          <img
            class="checked-img"
            :src="item.checked ? checkedImg : unCheckedImg"
            alt=""
          />
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import {
  ref,
  computed,
  reactive,
  onMounted,
  defineEmits,
  defineExpose,
} from 'vue';
import {
  getProfession,
  getChildMajorReq,
  getMajorByName,
} from '@/api/industryMap.js';
import antiShake from '@/utils/antiShake.js';

import searchIcon from '@/assets/images/industryMap/searchIcon.png';
import checkedImg from '@/assets/images/industryMap/checked.png';
import unCheckedImg from '@/assets/images/industryMap/unChecked.png';
const emit = defineEmits(['majorSearch', 'majorSelect']);
const currentSchool = ref(30);
const schoolLevelList = ref([
  { label: '本科', value: 30 },
  { label: '专科', value: 10 },
]);
const majorData = ref({});
const currentFirstMajor = ref({});
const currentSecondMajor = ref({});
const selectMajorMap = reactive(new Map());
const tagName = ref('');
const searchResult = ref([]);

const handleChangeSchool = (item) => {
  currentSchool.value = item.value;
  clearSelectedMajors(true);
  getMajorList();
};

// 获取一级专业
const getMajorList = async () => {
  let currentList = majorData.value[currentSchool.value];
  if (currentList && currentList.length) {
    selectFirstMajor(currentList[0]);
    return;
  }
  if (!currentList || !currentList.length) {
    const params = {
      cateType: currentSchool.value,
    };
    const res = await getProfession(params);
    if (res.code == 200) {
      majorData.value[currentSchool.value] = res.data || [];
      if (majorData.value[currentSchool.value].length) {
        selectFirstMajor(majorData.value[currentSchool.value][0]);
      }
    }
  }
};
//select first major
const selectFirstMajor = (item) => {
  currentFirstMajor.value = item;
  getChildMajor();
};
// get child major
const getChildMajor = async () => {
  if (
    !currentFirstMajor.value.children ||
    !currentFirstMajor.value.children.length
  ) {
    const res = await getChildMajorReq({
      positionTagId: currentFirstMajor.value.positionTagId,
    });
    currentFirstMajor.value.children = res.data || [];
    // 第三级添加字段checked
    currentFirstMajor.value.children.forEach((item) => {
      if (item.children && item.children.length) {
        item.children = item.children.map((_item) => {
          return { checked: false, ..._item };
        });
      }
    });
  }
  // 初始选中第二级第一个专业
  if (
    currentFirstMajor.value.children &&
    currentFirstMajor.value.children.length
  ) {
    selectSecondMajor(currentFirstMajor.value.children[0]);
  }
};

const selectSecondMajor = (item) => {
  currentSecondMajor.value = item;
};

// 选择专业
const handleSelectMajor = (item) => {
  item.checked = !item.checked;
  if (item.checked) {
    selectMajorMap.set(item.positionTagId, item);
  } else {
    selectMajorMap.delete(item.positionTagId);
  }
  submitSearch();
};
// 全选/反选
const toggleSelectAll = () => {
  const list = currentSecondMajor.value.children || [];
  const isAll = list.length && list.every((item) => item.checked);
  if (isAll) {
    // 反选：全部取消
    list.forEach((item) => {
      item.checked = false;
      selectMajorMap.delete(item.positionTagId);
    });
  } else {
    // 全选
    list.forEach((item) => {
      item.checked = true;
      selectMajorMap.set(item.positionTagId, item);
    });
  }
  submitSearch();
};
// 清空专业
const clearSelectedMajors = (flag = false) => {
  selectMajorMap.forEach((item) => {
    item.checked = false;
  });
  selectMajorMap.clear();
  if (flag) {
    submitSearch();
  }
};
const submitSearch = () => {
  tagName.value = '';
  emit('majorSearch', Array.from(selectMajorMap.values()));
};

// 选择下拉搜索查询
const handleChangeMajor = (val) => {
  console.log(val);

  clearSelectedMajors(); // 选择搜索项清空下面专业点选
  emit('majorSelect', val);
};

// 根据专业名称远程搜索专业
const loading = ref(false);
const handleRemoteMethod = async (query) => {
  if (query) {
    loading.value = true;
    const res = await getMajorByName({
      tagName: query,
      pageNo: 1,
      pageSize: 30,
    });
    if (res.code == 200) {
      searchResult.value = res.data;
    } else {
      searchResult.value = [];
    }
    loading.value = false;
  }
};

const isAllSelected = computed(() => {
  const list = currentSecondMajor.value.children || [];
  if (!list.length) return false;
  return list.every((item) => item.checked);
});
onMounted(() => {
  getMajorList();
});
</script>

<style lang="scss" scoped>
.major-list {
  display: flex;
  flex-direction: column;
  margin-top: 16px;
  width: 540px;
  background: #ffffff;
  box-shadow: 0px 2px 28px 6px rgba(184, 200, 219, 0.04);
  border-radius: 20px;
  .search-input {
    padding: 22px 28px 20px;
    .search-icon {
      width: 30px;
      margin-right: 10px;
    }
  }
  .header-tabs {
    padding: 0 28px;
    display: flex;
    align-items: center;
    .tabs-list {
      flex: 1;
      display: flex;
      font-weight: bold;
      font-size: 26px;
      color: #7f7f7f;
      .tab-item {
        margin-right: 40px;
        padding: 8px 0;
        &.active {
          color: #222222;
          position: relative;
          &::after {
            content: '';
            position: absolute;
            height: 4px;
            width: 32px;
            left: 50%;
            transform: translateX(-50%);
            bottom: 0;
            background: #0b6eff;
            border-radius: 3px;
          }
        }
      }
    }
    .reset-box {
      font-size: 24px;
      color: #999999;
      display: flex;
      align-items: center;
      img {
        width: 28px;
        height: 28px;
        margin-right: 6px;
      }
    }
  }
  .first-major {
    position: relative;
    &::after {
      content: '';
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      right: 0;
      width: 36px;
      height: 40px;
      background: linear-gradient(
        90deg,
        rgba(255, 255, 255, 0) 0%,
        #ffffff 100%
      );
    }
    .first-major-list {
      display: flex;
      overflow: hidden;
      overflow-x: auto;
      margin-top: 20px;
      margin-bottom: 24px;
      padding-left: 28px;

      .first-major-item {
        padding: 7px 18px;
        margin-right: 16px;
        white-space: nowrap;
        font-size: 20px;
        color: #7f7f7f;
        background: #f5f6f8;
        border-radius: 8px;
        &.active {
          background: #0b6eff;
          color: #ffffff;
        }
      }
    }
  }
  .major-child-main {
    flex: 1;
    height: 1px;
    display: flex;
    .major-second {
      width: 220px;
      height: 100%;
      overflow: hidden;
      overflow-y: auto;
      border-radius: 0 0 0 20px;
      background: #f9f9f9;
      .major-second-item {
        padding: 24px 28px;
        font-size: 24px;
        color: #666666;
        &.active {
          font-weight: bold;
          color: #0b6eff;
          background: #eff5ff;
        }
      }
    }
    .major-third {
      flex: 1;
      overflow: hidden;
      overflow-y: auto;
      .major-third-item {
        padding: 24px 28px;
        font-size: 24px;
        color: #666666;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .checked-img {
          width: 28px;
          height: 28px;
        }
        &.active {
          font-weight: bold;
          color: #0b6eff;
        }
      }
    }
  }
}
.first-major-list {
  &::-webkit-scrollbar {
    display: none;
  }
}
:deep(.el-select__wrapper) {
  padding: 0 20px;
  background: #f7f8fa;
  border-radius: 15px;
  box-shadow: none;
  line-height: normal;
}
:deep(.el-select__input) {
  height: 56px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 22px;
  color: #aaaaaa;
}
:deep(.el-select__placeholder.is-transparent) {
  font-size: 22px;
  color: #aaaaaa;
}
:deep(.el-select__selected-item) {
  .el-tag {
    color: #aaaaaa;
    font-size: 22px;
  }
  .el-tag__close {
    font-size: 20px;
    width: 20px;
    height: 20px;
  }
}
</style>
<style lang="scss">
.my-select {
  .el-select-dropdown__item {
    font-size: 24px;
    height: 56px;
    line-height: 56px;
    &.is-selected {
      color: #0b6eff;
      font-weight: 400;
      &::after {
        display: none;
      }
    }
  }
  .el-select-dropdown__empty {
    font-size: 24px;
    height: 56px;
    line-height: 56px;
  }
}
</style>
